<template>
  <div class="inventory-management">
    <el-card>
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>库存管理</h2>
        <el-button type="primary" @click="openAddDialog">新增库存</el-button>
      </div>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="货品名称">
          <el-input v-model="searchForm.goodsName" placeholder="请输入货品名称" clearable />
        </el-form-item>
        <el-form-item label="货品编号">
          <el-input v-model="searchForm.goodsCode" placeholder="请输入货品编号" clearable />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.goodsType" placeholder="请选择货品类型" clearable>
            <el-option v-for="item in productTypes" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="searchForm.warehouseId" placeholder="请选择仓库" clearable>
            <el-option v-for="item in warehouses" :key="item.warehouseId" :label="item.warehousename" :value="item.warehouseId" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchInventoryList">查询</el-button>
          <el-button @click="resetSearchForm">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 数据表格 -->
      <el-table :data="inventoryList" border style="width: 100%" v-loading="loading">
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="goodsCode" label="货品编号" width="120" />
        <el-table-column prop="goodsName" label="货品名称" width="150" />
        <el-table-column prop="goodsType" label="货品类型" width="120" />
        <el-table-column prop="spec" label="规格型号" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="warehouseName" label="仓库名称" width="120" />
        <el-table-column prop="locationName" label="库位名称" width="120" />
        <el-table-column prop="currentQty" label="当前库存" width="100" />
        <el-table-column prop="currentAmount" label="库存金额" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
              {{ scope.row.status === '1' ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteInventory(scope.row)">删除</el-button>
            <el-button type="info" size="small" @click="viewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="120px"
        class="inventory-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品编号" prop="goodsCode">
              <el-input v-model="formData.goodsCode" placeholder="请输入货品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品名称" prop="goodsName">
              <el-input v-model="formData.goodsName" placeholder="请输入货品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货品类型" prop="goodsType">
              <el-select v-model="formData.goodsType" placeholder="请选择货品类型" style="width: 100%">
                <el-option v-for="item in productTypes" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="spec">
              <el-input v-model="formData.spec" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="formData.unit" placeholder="请选择单位" style="width: 100%">
                <el-option v-for="item in units" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="条码" prop="barcode">
              <el-input v-model="formData.barcode" placeholder="请输入条码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="formData.warehouseId" placeholder="请选择仓库" style="width: 100%" @change="handleWarehouseChange">
                <el-option v-for="item in warehouses" :key="item.warehouseId" :label="item.warehousename" :value="item.warehouseId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位" prop="locationId">
              <el-select v-model="formData.locationId" placeholder="请选择库位" style="width: 100%">
                <el-option v-for="item in locations" :key="item.id" :label="item.librarylocationname" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="当前库存" prop="currentQty">
              <el-input-number v-model="formData.currentQty" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存金额" prop="currentAmount">
              <el-input-number v-model="formData.currentAmount" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio value="1">正常</el-radio>
                <el-radio value="0">异常</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入备注信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="库存详情" width="600px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="货品编号">{{ detailData.goodsCode }}</el-descriptions-item>
        <el-descriptions-item label="货品名称">{{ detailData.goodsName }}</el-descriptions-item>
        <el-descriptions-item label="货品类型">{{ detailData.goodsType }}</el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ detailData.spec }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ detailData.unit }}</el-descriptions-item>
        <el-descriptions-item label="条码">{{ detailData.barcode }}</el-descriptions-item>
        <el-descriptions-item label="仓库名称">{{ detailData.warehouseName }}</el-descriptions-item>
        <el-descriptions-item label="库位名称">{{ detailData.locationName }}</el-descriptions-item>
        <el-descriptions-item label="当前库存">{{ detailData.currentQty }}</el-descriptions-item>
        <el-descriptions-item label="库存金额">{{ detailData.currentAmount }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailData.status === '1' ? 'success' : 'danger'">
            {{ detailData.status === '1' ? '正常' : '异常' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注">{{ detailData.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
// 搜索表单
const searchForm = reactive({
  goodsName: '',
  goodsCode: '',
  goodsType: '',
  warehouseId: ''
})
// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
// 表格数据
const inventoryList = ref([])
const productTypes = ref<string[]>([])
const units = ref<any[]>([])
const warehouses = ref<{ warehouseId: string; warehousename: string }[]>([])
const locations = ref<{ id: string; librarylocationname: string }[]>([])
// 表单数据
const formData = reactive({
  id: '',
  goodsCode: '',
  goodsName: '',
  goodsType: '',
  spec: '',
  unit: '',
  barcode: '',
  warehouseId: '',
  locationId: '',
  currentQty: 0,
  currentAmount: 0,
  status: '1',
  remark: ''
})
// 详情数据
const detailData = reactive({
  goodsCode: '',
  goodsName: '',
  goodsType: '',
  spec: '',
  unit: '',
  barcode: '',
  warehouseName: '',
  locationName: '',
  currentQty: 0,
  currentAmount: 0,
  status: '',
  remark: ''
})
// 表单验证规则
const formRules: FormRules = {
  goodsCode: [
    { required: true, message: '请输入货品编号', trigger: 'blur' }
  ],
  goodsName: [
    { required: true, message: '请输入货品名称', trigger: 'blur' }
  ],
  goodsType: [
    { required: true, message: '请选择货品类型', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  locationId: [
    { required: true, message: '请选择库位', trigger: 'change' }
  ],
  currentQty: [
    { required: true, message: '请输入当前库存', trigger: 'blur' }
  ]
}
const formRef = ref<FormInstance>()
// 获取库存列表
const fetchInventoryList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }
    const { data } = await axios.post('/api/wcl/inventory/list', params)
    inventoryList.value = data?.data || []
    pagination.total = data?.total || 0
  } catch (error) {
    ElMessage.error('获取库存列表失败')
    console.error('获取库存列表失败:', error)
  } finally {
    loading.value = false
  }
}
// 获取货品类型
const fetchProductTypes = async () => {
  try {
    const { data } = await axios.get('http://localhost:9966/api/app/inventory/product-types')
    productTypes.value = data?.data || []
  } catch (error) {}
}
// 获取单位
const fetchUnits = async () => {
  try {
    const { data } = await axios.get('/api/wcl/inventory/units')
    units.value = data?.data || []
  } catch (error) {}
}
// 获取仓库列表
const fetchWarehouses = async () => {
  try {
    const { data } = await axios.get('api/app/ware-houser/ware-houser-list')
    warehouses.value = (data?.data || []).map((item: any) => ({
      warehouseId: item.warehouseId || item.id,
      warehousename: item.warehousename
    }))
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}
// 获取库位列表
const fetchLocations = async (warehouseId: string) => {
  if (!warehouseId) {
    locations.value = []
    return
  }
  try {
    const { data } = await axios.get(`/api/app/ware-houser/locations`, {
      params: { warehouseId }
    })
    locations.value = (data?.data || []).map((item: any) => ({
      id: item.id,
      librarylocationname: item.librarylocationname
    }))
  } catch (error) {
    console.error('获取库位列表失败:', error)
  }
}
// 仓库变化处理
const handleWarehouseChange = (warehouseId: string) => {
  formData.locationId = ''
  fetchLocations(warehouseId)
}
// 重置搜索表单
const resetSearchForm = () => {
  Object.assign(searchForm, {
    goodsName: '',
    goodsCode: '',
    goodsType: '',
    warehouseId: ''
  })
  pagination.currentPage = 1
  fetchInventoryList()
}
// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchInventoryList()
}
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchInventoryList()
}
// 打开新增对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '新增库存'
  dialogVisible.value = true
  resetFormData()
}
// 打开编辑对话框
const openEditDialog = (row: any) => {
  isEdit.value = true
  dialogTitle.value = '编辑库存'
  dialogVisible.value = true
  Object.assign(formData, row)
  if (row.warehouseId) {
    fetchLocations(row.warehouseId)
  }
}
// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: '',
    goodsCode: '',
    goodsName: '',
    goodsType: '',
    spec: '',
    unit: '',
    barcode: '',
    warehouseId: '',
    locationId: '',
    currentQty: 0,
    currentAmount: 0,
    status: '1',
    remark: ''
  })
}
// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      // 更新库存
      await axios.put('/api/wcl/inventory/update', formData)
      ElMessage.success('更新成功')
    } else {
      // 新增库存
      await axios.post('/api/wcl/inventory/create', formData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    fetchInventoryList()
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('操作失败')
    }
    console.error('提交表单失败:', error)
  } finally {
    submitLoading.value = false
  }
}
// 删除库存
const deleteInventory = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这条库存记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await axios.delete('/api/wcl/inventory/delete', {
      data: { id: row.id }
    })
    ElMessage.success('删除成功')
    fetchInventoryList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除库存失败:', error)
    }
  }
}
// 查看详情
const viewDetail = (row: any) => {
  Object.assign(detailData, row)
  detailDialogVisible.value = true
}
// 页面加载时初始化数据
onMounted(() => {
  fetchInventoryList()
  fetchProductTypes()
  fetchUnits()
  fetchWarehouses()
})
</script>
<style scoped>
.inventory-management {
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0;
  color: #303133;
}
.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.inventory-form {
  max-height: 500px;
  overflow-y: auto;
}
:deep(.el-form-item) {
  margin-bottom: 18px;
}
:deep(.el-input-number) {
  width: 100%;
}
</style> 